package com.test.activemq.queue;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class JMSProducer {

	
	public static void main (String [] args ){
		
		//连接工厂，用于生产connection
		ConnectionFactory connectionFactory ; 
		
		//连接
		Connection connection = null ;
		
		//会话  接受或者发送消息的线程
		Session session;
		
		//消息的目的地
		Destination destination;
		
		//消息生产者
		MessageProducer messageProducer;
		
		connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,
				ActiveMQConnection.DEFAULT_PASSWORD, ActiveMQConnection.DEFAULT_BROKER_URL);
		try {
			connection = connectionFactory.createConnection();
			connection.start();//启动连接
			//创建session两个参数，是否开启事务,消息确认的方式
			session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
			destination = session.createQueue("Testqueue1");//创建消息队列
			messageProducer = session.createProducer(destination);//创建消息生产者
			sendMessage(session, messageProducer);
			session.commit();
		} catch (JMSException e) {
			e.printStackTrace();
		}finally{
			if(null != connection){
				try {
					connection.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	/**
	 * 发送消息 
	 * @param session
	 * @param messageProducer
	 * @throws JMSException
	 */
	public static void sendMessage(Session session , MessageProducer messageProducer) throws JMSException{
		for(int i = 0 ;i<10;i++){
			TextMessage msg = session.createTextMessage("ActiveMq 发送的msg:"+i);
			System.out.println("发送消息 "+i);
			messageProducer.send(msg);
		}
	}
}
